package cn.edu.fudan.bdke.ncov.qa.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * 字典工具类
 *
 * @author xym
 * @since 1.0
 */
public class DictUtil {
    private DictUtil() {
    }

    /**
     * 支持的字典文件类型：一行单词或多个用空格分割的单词
     *
     * @param dictFilePath 字典路径
     * @return 字典中的单词列表
     */
    public static List<String> load(String dictFilePath) {
        BufferedReader br = null;
        List<String> dict = new ArrayList<>();
        try {
            br = new BufferedReader(new FileReader(dictFilePath));
            String curLine = null;
            while ((curLine = br.readLine()) != null) {
                String[] words = curLine.split("\\s+");
                dict.addAll(Arrays.asList(words));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dict;
    }

    /**
     * 加载字典，行内单词由空格分割
     *
     * @param dictFilePath 字典路径
     * @param label        true：表示每行的最后一个单词是标签
     *                     false：表示每行的首个单词是标签
     */
    public static Map<String, List<String>> loadByLine(String dictFilePath, boolean label) {
        BufferedReader br = null;
        Map<String, List<String>> dict = new HashMap<>();
        try {
            br = new BufferedReader(new FileReader(dictFilePath));
            String curLine = null;
            while ((curLine = br.readLine()) != null) {
                String[] words = curLine.split("\\s+");
                List<String> wordList = new LinkedList<>(Arrays.asList(words));
                if (label) {
                    wordList.remove(wordList.size() - 1);
                    dict.put(words[words.length - 1], wordList);
                } else {
                    wordList.remove(0);
                    dict.put(words[0], wordList);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dict;
    }
}
